package com.lxs.legou.order.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.lxs.legou.order.config.TokenDecode;
import com.lxs.legou.order.po.OrderItem;
import com.lxs.legou.order.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @Auther: Mcb
 * @Date: 2022/1/9 22:48
 * @Description:
 */
@RestController
@RequestMapping("/cart")
@CrossOrigin
public class CartController {

    @Autowired
    private CartService cartService;
    @Autowired
    private TokenDecode tokenDecode;

    /**
     * 添加购物车
     * @param skuId
     * @param num
     * @return
     * @throws IOException
     */
    @RequestMapping("/add")
    public ResponseEntity add(Long skuId, Integer num){
        Map<String, String> userInfo = null;
        boolean addState = false;
        try {
            userInfo = tokenDecode.getUserInfo();
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        if (userInfo!= null) {
            addState = cartService.add(skuId, num, userInfo.get("user_name"));
        }
        return addState? ResponseEntity.ok("添加成功"): ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
    }

    /**
     * 删除购物车
     * @param skuId
     * @return
     */
    @RequestMapping("/delete")
    public ResponseEntity delete(Long skuId){
        Map<String, String> userInfo = null;
        boolean deleteState = false;
        try {
             userInfo = tokenDecode.getUserInfo();
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        if (userInfo!= null) {
            deleteState = cartService.delete(skuId, userInfo.get("user_name"));
        }
        return deleteState? ResponseEntity.ok("删除成功"): ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
    }


    /**
     * 购物车列表
     * @return
     */
    @RequestMapping("/list")
    public List<OrderItem> list(){
        Map<String, String> userInfo = null;
        try {
            userInfo = tokenDecode.getUserInfo();
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return cartService.list(userInfo.get("user_name"));
    }
}
